package com.elinkway.infinitemovies.selfdata;

import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.async.RequestResultListener;
import com.elinkway.infinitemovies.bean.CommonBean;
import com.elinkway.infinitemovies.selfdata.bean.MyRecordBean;
import com.elinkway.infinitemovies.selfdata.dao.MyDataDao;
import com.elinkway.infinitemovies.selfdata.dao.RealmDaoManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import io.realm.OrderedRealmCollectionSnapshot;
import io.realm.RealmResults;

/**
 * Author: liuxiaojiang(xiao)
 * Date: 2017-07-07
 * Time: 19:34
 * Description: FIXME
 */
public class UploadUtil {
    private MyDataDao mDao;
    private RealmResults<MyRecordBean> mResults;
    private OrderedRealmCollectionSnapshot<MyRecordBean> mResultsSnapshot;
    private List<MyRecordBean> mList;

    public void upload(){
        mDao = RealmDaoManager.getMyDataDao();
        mResults = mDao.findAll();
        if(mResults == null || mResults.size() == 0){
            return;
        }
        mResultsSnapshot = mResults.createSnapshot();
        if(mResults.size() > 2000){     //数据大于2000条删除
            mDao.delete(mResults);
            return;
        }
        mList = mDao.realmResultsToList(mResults);
        if(mList == null || mList.size() <= 0){
           return;
        }
        List<JSONObject> jsonList = new ArrayList<>();
        for (MyRecordBean bean: mList){
            try {
                jsonList.add(new JSONObject(bean.getRecordVlaue()));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        SelfDataReportTask task = new SelfDataReportTask(MoviesApplication.getInstance(), jsonList);
        task.setmListener(new RequestResultListener<CommonBean>() {
            @Override
            public boolean onRequestFailed() {
                //上传失败后保留原有数据不做任何处理
                return false;
            }

            @Override
            public void onRequestSuccess(int updateId, CommonBean result) {
                if("200".equals(result.getCode())){
                    if(mResultsSnapshot != null && mDao != null){
                        mDao.deleteSnapshot(mResultsSnapshot);
                    }
                }
            }

            @Override
            public void onPreRequest() {

            }
        });
        task.start();
    }
}
